//
//  AppDelegate.swift
//  ddx0513
//
//  Created by jiang yongbin on 15/5/13.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit
//var db:SQLiteDB!

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate {

    var window: UIWindow?
    let db = SQLiteDB.sharedInstance()
    var _polyvSettings: PolyvSettings?
   

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        UINavigationBar.appearance().setBackgroundImage(UIImage(named: "导航.png"), forBarMetrics: UIBarMetrics.Default)
        UINavigationBar.appearance().tintColor = UIColor.whiteColor()
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
        
        //py 注册消息推送
        var str:NSString = UIDevice.currentDevice().systemVersion
        var version:Float = str.floatValue
       
     
        if version >= 8.0 {
            UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))
            UIApplication.sharedApplication().registerForRemoteNotifications()
        } else {
            UIApplication.sharedApplication().registerForRemoteNotificationTypes( UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound | UIRemoteNotificationType.Alert)
        }

        
        //集成极光推送
        
        APService.registerForRemoteNotificationTypes(UIUserNotificationType.Badge.rawValue | UIUserNotificationType.Badge.rawValue | UIUserNotificationType.Alert.rawValue , categories: nil)
        
        APService.setupWithOption(launchOptions)
        
     //   APService.registerForRemoteNotificationTypes(<#types: UInt#>, categories: nil)
        
        /*(UIUserNotificationTypeBadge |
            UIUserNotificationTypeSound |
            UIUserNotificationTypeAlert, categories: nil)
        
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
            UIUserNotificationTypeSound |
            UIUserNotificationTypeAlert)
            categories:nil];

        
        
        self.window = UIWindow.initialize().in
        
        
            [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
        self.window.backgroundColor = [UIColor whiteColor];
        [self.window makeKeyAndVisible];
        
        
        // Required
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            //可以添加自定义categories
            [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                UIUserNotificationTypeSound |
                UIUserNotificationTypeAlert)
                categories:nil];
        } else {
            //categories 必须为nil
            [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                UIRemoteNotificationTypeSound |
                UIRemoteNotificationTypeAlert)
                categories:nil];
        }
        
        // Required
        [APService setupWithOption:launchOptions];
        
        */
        
        
        
        //设置播放器参数
        var downloadPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
        var downloadDir = downloadPath + "/videos/"
        PolyvSettings.setDownloadDir(downloadDir)
        _polyvSettings = PolyvSettings()
        _polyvSettings?.initVideoSettings(DBUtils.mem.vSecretKey, readtoken: DBUtils.mem.vReadToken, writetoken: DBUtils.mem.vWriteToken, userId: DBUtils.mem.vUserId)
        
        //读取用户名、密码、自动登录参数
        DBUtils.load()
        if (DBUtils.mem.loginName != "" && DBUtils.mem.password != "" && DBUtils.mem.loginStatus) {
            let a = ["mobile": DBUtils.mem.loginName, "pwd": DBUtils.mem.password]
            NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLLogin(), parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: login, interErrorHandler: nil, jsonErrorHandler: nil)
        }
        
        //Bugly
//        CrashReporter.sharedInstance().enableLog(true)
        CrashReporter.sharedInstance().installWithAppId("900004867")
        
        //向微信注册
        WXApi.registerApp("wxf1d9417dff881319", withDescription: "ddx1.0")
        
        
        //add by py 添加失败提醒
        let err = db.execute(
            "create table if not exists t_user(content varchar(255))"
        )
        
        
        
        // Override point for customization after application launch.
        return true
    }
                                                                                                                                                                                                               
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        _polyvSettings?.reloadSettings()
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func login(json: JSON) {
        var userId = json["userid"].int
        var nickName = json["nickname"].string
        var imgUrl = json["imgurl"].string
        var pushAlias = json["push_alias"].string
        var pushTag = json["push_tag"].string
        var imUsername = json["im_username"].string
        var imPassword = json["im_password"].string
        var vipType = json["vip_type"].string
        var vipBegin = json["vip_begin"].int64
        var vipExpire = json["vip_expire"].int64
        var token = json["token"].string
        
        DBUtils.mem.loginStatus = true
        if let a = userId {
            DBUtils.mem.userId = a
        }
        if let a = nickName {
            DBUtils.mem.nickName = a
        }
        if let a = imgUrl {
            DBUtils.mem.imgURL = a
        }
        if let a = pushAlias {
            DBUtils.mem.pushAlias = a
        }
        if let a = pushTag {
            DBUtils.mem.pushTag = a
        }
        if let a = imUsername {
            DBUtils.mem.imUsername = a
        }
        if let a = imPassword {
            DBUtils.mem.imPassword = a
        }
        if let a = token {
            DBUtils.mem.token = a
        }
        if let a = vipType {
            DBUtils.mem.vipType = a
        }
        if let a = vipBegin {
            DBUtils.mem.vipBegin = a
        }
        if let a = vipExpire {
            DBUtils.mem.vipExpire = a
        }
    }
    
    // MARK: - 处理横竖屏事宜
//    func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
//        if (DBUtils.mem.isFullScreen) {
//            return Int(UIInterfaceOrientationMask.LandscapeRight.rawValue)
//        } else {
//            return Int(UIInterfaceOrientationMask.Portrait.rawValue)
//        }
//    }
    
    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
        if (url.host == "safepay") {
            AlipaySDK.defaultService().processOrderWithPaymentResult(url, standbyCallback: { (ret: [NSObject : AnyObject]!) -> Void in
                let ret1 = ret as! [String: String]
                
                let notification = NSNotification(name: StringUtils.AlipayNotification, object: ret1["resultStatus"]!)
                NSNotificationCenter.defaultCenter().postNotification(notification)
            })
        } else if (url.host == "pay") {
            return WXApi.handleOpenURL(url, delegate: self)
        }
        
        return true
    }
    
    func onResp(resp: BaseResp!) {
        if (resp.isKindOfClass(PayResp)) {
            let notification = NSNotification(name: StringUtils.WeipayNotification, object: resp)
            NSNotificationCenter.defaultCenter().postNotification(notification)
        }
    }
    


    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        var token:String = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
        
        APService.registerDeviceToken(deviceToken)
        
  
 
        
 
     //    [APService registerDeviceToken:deviceToken];
        //将token发送到服务器
    }
    
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        var alert:UIAlertView = UIAlertView(title: "", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK")
        alert.show()
    }
    
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

        
        APService.handleRemoteNotification(userInfo)
        let notif = userInfo as NSDictionary

        let apsDic = notif.objectForKey( "aps" ) as! NSDictionary
        let alertDic = apsDic.objectForKey( "alert" ) as! String
 
          //  handleRemoteNotification:userInfo];
        //sqlite
        //获取数据库实例
        //let db = SQLiteDB.sharedInstance()
        //如果表还不存在则创建表
        //let a = db.query("delete from t_user")
        let messagedata = db.query("select * from t_user")

        let sql = "insert into t_user(content) values('\(alertDic)')"

        //通过封装的方法执行sql
        let result = db.execute(sql)
        
        
    }
    
           
    
    
}

